package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.market;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.NumberTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.TreeResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsCancelAuditResponse;
import com.gzhryc.net_marketing.core.GoodsTypeUtils;
import com.gzhryc.net_marketing.core.models.GoodsTypeItem;
import com.gzhryc.net_marketing.supplier.Supplier;
import com.gzhryc.net_marketing.supplier.SupplierManager;
import com.gzhryc.net_marketing.supplier.erp.dao.db.SupplierGoods;
import com.gzhryc.net_marketing.supplier.erp.dao.db.SupplierGoodsSpace;
import com.gzhryc.net_marketing.supplier.erp.dao.enums.SupplierGoodsEnum;
import com.gzhryc.net_marketing.supplier.erp.services.SupplierGoodsService;
import com.gzhryc.net_marketing.supplier.erp.services.SupplierGoodsSpaceService;
import com.gzhryc.net_marketing.supplier.erp.services.dto.SupplierGoodsSearch;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.ResourceAPIServer;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import com.gzhryc.net_marketing.core.enums.EGoodsClassify;
import com.gzhryc.net_marketing.api.CloudGoodsAPIService;
import com.gzhryc.net_marketing.core.models.GoodsSpaceItem;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsApplyAuditRequest;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsApplyAuditResponse;
import com.gzhryc.net_marketing.core.enums.EGoodsAuditState;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class GoodsController {

    static Logger log = Logger.getLogger(GoodsController.class);

    @Route(value = { "/market/goods/list.html" })
    public String list(HttpServletRequest request) {
        request.setAttribute("stateList", SupplierGoodsEnum.State.values());
        request.setAttribute("auditStateList", SupplierGoodsEnum.AuditState.values());
        request.setAttribute("classifyList", EGoodsClassify.values());
        return "/market/goods/list.html";
    }

    @Route(value = "/market/goods/list.data")
    public ListResult<SupplierGoods> listData(HttpServletRequest request) {
        ListResult<SupplierGoods> result = new ListResult<SupplierGoods>(DtoConstants.NULL_DATA,"暂无数据");
        Supplier supplier = SupplierManager.getSupplier();
        if(supplier != null) {
	        SupplierGoodsSearch search = WebUtils.getParameter(request, SupplierGoodsSearch.class);
	        Integer pageNo = WebUtils.getInteger(request, "page", 1);
	        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
	
	        result.getBody().setTotal(SupplierGoodsService.self(supplier.getJdbcKey()).countJoinBySearch(search));
	        result.getBody().setData(SupplierGoodsService.self(supplier.getJdbcKey()).findJoinBySearch(search, pageNo, pageLimit));
	
	        if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
	            result.setCode(DtoConstants.SUCCESS, null);
	        }
        }
        return result;
    }

    @Route(value = { "/market/goods/add.html" })
    public String add(HttpServletRequest request) {
        request.setAttribute("stateList", SupplierGoodsEnum.State.values());
        request.setAttribute("classifyList", EGoodsClassify.values());
        
        String resDomain = PropertyTools.get().getString("resDomain");
        String resToken = PropertyTools.get().getString("resToken");
        String resId = PropertyTools.get().getString("resId");
        
        ResourceAPIServer resAPISer = new ResourceAPIServer();
        resAPISer.initial(resDomain, resToken, resId);
        request.setAttribute("marketResDomain", resDomain);
        request.setAttribute("marketResToken",ResourceAPIServer.self().buildTransferToken());
        
        Supplier supplier = SupplierManager.getSupplier();
        if(supplier != null) {
        	request.setAttribute("supplierId", supplier.getId());
        }else {
        	request.setAttribute("supplierId", "0");
        }
        
        GoodsTypeUtils.initial();//初始化
        
        return "/market/goods/edit.html";
    }

    @Route(value = { "/market/goods/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增商品失败");
        Supplier supplier = SupplierManager.getSupplier();
        SupplierGoods goods = WebUtils.getParameter(request, SupplierGoods.class);
        if (goods != null && StringUtils.isNotBlank(goods.getName()) && supplier != null) {
            Double payMoneyStr = WebUtils.getDouble(request,"payMoneyStr");
            if(payMoneyStr == null) {
                result.setMsg("请填写零售价格");
                return result;
            }
            String typeCodes = WebUtils.getString(request,"types");
            if(StringUtils.isBlank(typeCodes)){
                result.setMsg("请填写商品类型");
                return result;
            }
            String[] codes = typeCodes.split(",");
            String[] names = GoodsTypeUtils.findByCodes(codes);
            if(names != null && names.length > 0 && names.length == codes.length){
                goods.setTypeCodes(typeCodes);
                goods.setTypeNames(StringUtils.join(names,","));
                //设置商品分类
                GoodsTypeItem goodsTypeItem = GoodsTypeUtils.getByCode(codes[0]);
                goods.setClassify(goodsTypeItem.getClassify());
            }else{
                result.setMsg("填写的商品类型有误");
                return result;
            }

            goods.setPayMoney(NumberTools.changeMoney(payMoneyStr));
            try {
                if (SupplierGoodsService.self(supplier.getJdbcKey()).add(goods)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = { "/market/goods/update.html" })
    public String update(HttpServletRequest request) {
    	Supplier supplier = SupplierManager.getSupplier();
    	if(supplier != null) {
	        Long id = WebUtils.getLong(request, "id");
	        SupplierGoods goods = SupplierGoodsService.self(supplier.getJdbcKey()).getJoinById(id);
	        if(goods != null) {
	            WebUtils.setAttribute(request, goods);
	            if(StringUtils.isNotBlank(goods.getTypeCodes())) {
	                String[] codes = goods.getTypeCodes().split(",");
	                request.setAttribute("types", codes);
	            }
	        }
    	}
    	
        request.setAttribute("stateList", SupplierGoodsEnum.State.values());
        request.setAttribute("classifyList", EGoodsClassify.values());
        
        String resDomain = PropertyTools.get().getString("resDomain");
        String resToken = PropertyTools.get().getString("resToken");
        String resId = PropertyTools.get().getString("resId");
        
        ResourceAPIServer resAPISer = new ResourceAPIServer();
        resAPISer.initial(resDomain, resToken, resId);
        request.setAttribute("marketResDomain", resDomain);
        request.setAttribute("marketResToken",ResourceAPIServer.self().buildTransferToken());
        
    	GoodsTypeUtils.initial();//初始化
    	
        return "/market/goods/edit.html";
    }

    @Route(value = { "/market/goods/info.html" })
    public String info(HttpServletRequest request) {
    	Supplier supplier = SupplierManager.getSupplier();
        Long id = WebUtils.getLong(request, "id");
        SupplierGoods goods = SupplierGoodsService.self(supplier.getJdbcKey()).getJoinById(id);
        if(goods != null) {
        	String resDomain = PropertyTools.get().getString("marketResDomain");
            String[] imgPaths = goods.getImgPaths();
            if (imgPaths != null && imgPaths.length > 0) {
                for (int i = 0; i < imgPaths.length; i++) {
                    imgPaths[i] = WebUtils.setHttpDomain(resDomain,imgPaths[i]);
                }
            }
            goods.setImgPaths(imgPaths);
            String[] detailImgPaths = goods.getDetailImgPaths();
            if (detailImgPaths != null && detailImgPaths.length > 0) {
                for (int i = 0; i < detailImgPaths.length; i++) {
                    detailImgPaths[i] = WebUtils.setHttpDomain(resDomain,detailImgPaths[i]);
                }
            }
            goods.setDetailImgPaths(detailImgPaths);
            goods.setThumbnailImg(WebUtils.setHttpDomain(resDomain,goods.getThumbnailImg()));
            WebUtils.setAttribute(request, goods);
            Long total = SupplierGoodsSpaceService.self(supplier.getJdbcKey()).countByGoodsId(id);
            if (total != null && total > 0) {
                request.setAttribute("hasGoodsSpace", true);
            }
            WebUtils.setAttribute(request, goods);

        }
        return "/market/goods/info.html";
    }

    @Route(value = { "/market/goods/update.do" })
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改商品失败");
        Supplier supplier = SupplierManager.getSupplier();
        SupplierGoods goods = WebUtils.getParameter(request, SupplierGoods.class);
        if (goods != null && StringUtils.isNotBlank(goods.getName()) && supplier != null) {
            Double payMoneyStr = WebUtils.getDouble(request,"payMoneyStr");
            if(payMoneyStr == null) {
                result.setMsg("请填写零售价格");
                return result;
            }
            String typeCodes = WebUtils.getString(request,"types");
            if(StringUtils.isBlank(typeCodes)){
                result.setMsg("请填写商品类型");
                return result;
            }
            String[] codes = typeCodes.split(",");
            String[] names = GoodsTypeUtils.findByCodes(codes);
            if(names != null && names.length > 0 && names.length == codes.length){
                goods.setTypeCodes(typeCodes);
                goods.setTypeNames(StringUtils.join(names,","));
                //设置商品分类
                GoodsTypeItem goodsTypeItem = GoodsTypeUtils.getByCode(codes[0]);
                goods.setClassify(goodsTypeItem.getClassify());
            }else{
                result.setMsg("填写的商品类型有误");
                return result;
            }
            goods.setPayMoney(NumberTools.changeMoney(payMoneyStr));
            try {
                if (SupplierGoodsService.self(supplier.getJdbcKey()).updateNotNull(goods)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = { "/market/goods/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除商品失败");
        Supplier supplier = SupplierManager.getSupplier();
        Long id = WebUtils.getLong(request, "id");
        if (id != null && supplier != null) {
            try {
                if (SupplierGoodsService.self(supplier.getJdbcKey()).deleteById(id)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = { "/market/goods/up.do" })
    public AjaxResult doUp(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "上架商品失败");
        Supplier supplier = SupplierManager.getSupplier();
        Long id = WebUtils.getLong(request, "id");
        if (id != null && supplier != null) {
            try {
                if (SupplierGoodsService.self(supplier.getJdbcKey()).upGoods(id)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = { "/market/goods/down.do" })
    public AjaxResult doDown(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "下架商品失败");
        Supplier supplier = SupplierManager.getSupplier();
        Long id = WebUtils.getLong(request, "id");
        if (id != null && supplier != null) {
            try {
                if (SupplierGoodsService.self(supplier.getJdbcKey()).downGoods(id)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = { "/market/goods/audit/apply.do" })
    public AjaxResult applyAudit(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "发布商品失败");
        Supplier supplier = SupplierManager.getSupplier();
        Long id = WebUtils.getLong(request, "id");
        SupplierGoods goods = SupplierGoodsService.self(supplier.getJdbcKey()).getJoinById(id);
        if(goods != null) {
            if(SupplierGoodsEnum.AuditState.Error.index().equals(goods.getAuditState())){
                result.setMsg("审核失败，请修改后再次提交审核");
                return result;
            }

            if(SupplierGoodsEnum.AuditState.Success.index().equals(goods.getAuditState())){
                result.setMsg("审核已通过，无需再次提交");
                return result;
            }

            String resDomain = PropertyTools.get().getString("resDomain");

            GoodsApplyAuditRequest apiReq = new GoodsApplyAuditRequest();
            ClassTools.copy(apiReq.getBody(),goods);
            //处理商品图片
            String[] imgPaths = goods.getImgPaths();
            if (imgPaths != null && imgPaths.length > 0) {
                for (int i = 0; i < imgPaths.length; i++) {
                    imgPaths[i] = WebUtils.setHttpDomain(resDomain,imgPaths[i]);
                }
            }
            apiReq.getBody().setImgs(StringUtils.join(imgPaths,"|"));
            //处理详情图片
            String[] detailImgPaths = goods.getDetailImgPaths();
            if (detailImgPaths != null && detailImgPaths.length > 0) {
                for (int i = 0; i < detailImgPaths.length; i++) {
                    detailImgPaths[i] = WebUtils.setHttpDomain(resDomain,detailImgPaths[i]);
                }
            }
            apiReq.getBody().setDetailImgs(StringUtils.join(detailImgPaths,"|"));

            apiReq.getBody().setGoodsId(goods.getId());
            apiReq.getBody().setSupplierId(supplier.getId());
            if(SupplierGoodsEnum.AuditState.Auditing.index().equals(goods.getAuditState())){
                apiReq.getBody().setAuditId(goods.getAuditId());
            }
            //商品规格
            List<SupplierGoodsSpace> goodsSpaceList = SupplierGoodsSpaceService.self(supplier.getJdbcKey()).findByGoodsId(goods.getId());
            if(goodsSpaceList != null && goodsSpaceList.size() > 0){
                apiReq.getBody().setSpaceItemList(new ArrayList<>());
                for(SupplierGoodsSpace goodsSpace : goodsSpaceList){
                    //TODO 这里的商品状态需要注意，目前本地商品状态与云端保持同步，不排除以后扩展
                    GoodsSpaceItem item = ClassTools.copy(new GoodsSpaceItem(),goodsSpace);
                    item.setThumbnailImg(WebUtils.setHttpDomain(resDomain,item.getThumbnailImg()));
                    apiReq.getBody().getSpaceItemList().add(item);
                }
            }
            GoodsApplyAuditResponse apiResp = CloudGoodsAPIService.self().goodsApplyAudit(apiReq);
            if(apiResp != null){
                if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                    Integer auditState = SupplierGoodsEnum.AuditState.Auditing.index();
                    if (EGoodsAuditState.Success.index().equals(apiResp.getBody().getAuditState())) {
                        auditState = SupplierGoodsEnum.AuditState.Success.index();
                    } else if (EGoodsAuditState.Fail.index().equals(apiResp.getBody().getAuditState())
                            || EGoodsAuditState.Close.index().equals(apiResp.getBody().getAuditState())) {
                        auditState = SupplierGoodsEnum.AuditState.Error.index();
                    }
                    try {
						if (SupplierGoodsService.self(supplier.getJdbcKey()).updateAuditResult(goods.getId(), apiResp.getBody().getAuditId()
								, auditState, apiResp.getBody().getGoodsCode(), apiResp.getBody().getAuditNote())) {
						    result.setCode(DtoConstants.SUCCESS, null);
						}
					} catch (LogicException e) {
						result.setMsg(e.getMessage());
					}
                }else if(StringUtils.isNotBlank(apiResp.getMsg())){
                    result.setMsg(apiResp.getMsg());
                }
            }else{
                result.setMsg("发送审核无响应");
            }
        }
        return result;
    }

    @Route(value = { "/market/goods/audit/cancel.do" })
    public AjaxResult cancelAudit(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "取消发布商品失败");
        Supplier supplier = SupplierManager.getSupplier();
        Long id = WebUtils.getLong(request, "id");
        SupplierGoods goods = SupplierGoodsService.self(supplier.getJdbcKey()).getJoinById(id);
        if(goods != null) {
            if(SupplierGoodsEnum.AuditState.Wait.index().equals(goods.getAuditState())
                    || SupplierGoodsEnum.AuditState.Error.index().equals(goods.getAuditState())){
                result.setMsg("商品未发布");
                return result;
            }
            GoodsCancelAuditResponse apiResp = CloudGoodsAPIService.self().goodsCancelAudit(goods.getAuditId());
            if(apiResp != null){
                if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                    try {
						if (SupplierGoodsService.self(supplier.getJdbcKey()).updateAuditResult(goods.getId(), apiResp.getBody().getAuditId(), 
								SupplierGoodsEnum.AuditState.Cancel.index(), apiResp.getBody().getGoodsCode(), apiResp.getBody().getAuditNote())) {
						    result.setCode(DtoConstants.SUCCESS, null);
						}
					} catch (LogicException e) {
						result.setMsg(e.getMessage());
					}
                }else if(DefaultAPICodeConstants.NULL_DATA.equals(apiResp.getCode())){
                    if (SupplierGoodsService.self(supplier.getJdbcKey()).cancelAudit(goods.getId())) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }else if(StringUtils.isNotBlank(apiResp.getMsg())){
                    result.setMsg(apiResp.getMsg());
                }
            }else{
                result.setMsg("取消发布无响应");
            }
        }
        return result;
    }

    @Route("/market/goodsType/tree/select.data")
    public TreeResult<GoodsTypeItem> select(HttpServletRequest request, HttpServletResponse response){
        TreeResult<GoodsTypeItem> result = new TreeResult<GoodsTypeItem>(DtoConstants.SUCCESS);
        result.getBody().setData(GoodsTypeUtils.getGoodsTypeItems());
        return result;
    }
}
